package RuntimeInfo;

import ShapeModel.CADShape;

import java.io.*;

public class IOHandle {
    static ObjectOutputStream out;
    static ObjectInputStream in;

    /**
     * 从指定的file中读取文件信息到系统，进而完成绘图
     *
     * @param f 指定的文件对象
     */
    public static void loadFile(File f) throws IOException, ClassNotFoundException {

        State.curFile = f;
        int shapeNum;
        in = new ObjectInputStream(new FileInputStream(f));
        try{
            shapeNum = in.readInt();
            System.out.println("here2");
            for (int i = 0; i < shapeNum; ++i) {
                State.shapeList.add((CADShape) in.readObject());
            }
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }
        finally {// 无论如何都要正确关闭
            in.close();
        }



    }


    /**
     * 对当前文件进行保留操作，先写入shape长度，再依次读出shape的数据
     */
    public static void saveFile() throws IOException {
        out = new ObjectOutputStream(new FileOutputStream(State.curFile));
        try {
            out.writeInt(State.shapeList.size());
            for (CADShape shape : State.shapeList) {
                out.writeObject(shape);
            }
        } finally {// 无论如和都要正确关闭,如果有错就抛出
            out.close();
        }
    }
}
